package com.study.springboot.common.mvc;

import com.study.springboot.common.constant.ErrorRespStatusEnum;
import com.study.springboot.common.constant.GlobalConsts;
import com.study.springboot.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.NodeImpl;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author wei.zhao
 * @Description: 异常处理器
 * @date 2021年12月01日 22:45
 */
@Slf4j
@RestControllerAdvice
public class CustomedExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RespData handleException(Exception ex) {
        return WebUtil.callback(ErrorRespStatusEnum.SERVICE_ERROR);
    }

    /**
     * 处理请求参数格式异常：@RequestBody上validate失败后抛出的MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RespData MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getAllErrors().stream().map(e ->
                ((FieldError) e).getField() + e.getDefaultMessage()
        ).collect(Collectors.joining(GlobalConsts.COMMA));
        log.info("参数校验不合法：{}", message);
        return WebUtil.callback(ErrorRespStatusEnum.METHOD_ARGUMENT_NOT_VALID, null, message);
    }

    /**
     * 处理请求参数格式异常：@RequestParam、@PathVariable上validate失败后抛出的ConstraintViolationException异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RespData ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        String message = ex.getConstraintViolations().stream().map(e -> {
            PathImpl pathImpl = (PathImpl) e.getPropertyPath();
            NodeImpl leafNode = pathImpl.getLeafNode();
            return leafNode.getName() + e.getMessage();
        }).collect(Collectors.joining(GlobalConsts.COMMA));
        log.info("参数校验不合法：{}", message);
        return WebUtil.callback(ErrorRespStatusEnum.METHOD_ARGUMENT_NOT_VALID, null, message);
    }

    @ExceptionHandler(CustomedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RespData handleException(CustomedException ex) {
        return WebUtil.callback(ex.getErrorRespStatusEnum());
    }

}
